package com.seecen.HJM.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.HJM.constant.JwtClaimsConstant;
import com.seecen.HJM.constant.MessageConstant;
import com.seecen.HJM.mapper.CommentMapper;
import com.seecen.HJM.model.dto.CommentDTO;
import com.seecen.HJM.model.dto.CommentPlaylistDTO;
import com.seecen.HJM.model.dto.CommentSongDTO;
import com.seecen.HJM.model.dto.CommentSongDto2;
import com.seecen.HJM.model.entity.Comment;
import com.seecen.HJM.model.vo.CommentVo2;
import com.seecen.HJM.result.DataVo;
import com.seecen.HJM.result.PageResult;
import com.seecen.HJM.service.CommentService;
import com.seecen.HJM.util.ThreadLocalUtil;
import com.seecen.HJM.util.TypeConversionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author jiachen
 * @description 针对表【tb_comment】的数据库操作Service实现
 * @createDate 2025-09-28 15:55:40
 */
@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
        implements CommentService{

    @Autowired
    private CommentMapper commentMapper;

    // 缓存键由分页参数和搜索内容组成，确保缓存唯一性

    @Cacheable(
            value = "commentCache",
            key = "#commentDTO.pageNum + '-' + #commentDTO.pageSize + '-' + (#commentDTO.content ?: '') + '-' + (#commentDTO.type ?: '')"
    )
    @Override
    public DataVo<PageResult<Comment>> getAllComment(CommentDTO commentDTO) {
        // 1. 创建分页对象
        Page<Comment> page = new Page<>(commentDTO.getPageNum(), commentDTO.getPageSize());

        // 2. 构建查询条件
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        // 按内容模糊查询（忽略空值）
        if (commentDTO.getContent() != null && !commentDTO.getContent().trim().isEmpty()) {
            queryWrapper.like("content", commentDTO.getContent().trim());
        }
        Integer commentType = commentDTO.getType();
        if (commentType != null && (commentType == 0 || commentType == 1)) {
            queryWrapper.eq("type", commentDTO.getType());
        }

        // 3. 执行分页查询
        IPage<Comment> commentIPage = baseMapper.selectPage(page, queryWrapper);

        // 4. 处理查询结果
        if (commentIPage.getRecords().isEmpty()) {
            // 无数据时返回空列表
            return DataVo.success(MessageConstant.DATA_NOT_FOUND, new PageResult<>(0L, null));
        }

        // 5. 封装分页结果并返回
        PageResult<Comment> pageResult = new PageResult<>(
                commentIPage.getTotal(),  // 总记录数
                commentIPage.getRecords() // 当前页数据列表
        );
        return DataVo.success(pageResult);
    }
    // ---------------------- 新增批量删除方法（核心） ----------------------
    @Override
    @CacheEvict(cacheNames = {"songCache", "playlistCache", "commentCache"}, allEntries = true)
    public DataVo adminDeleteComment(List<Long> commentIds) {
        // 1. 基础校验：ID列表不能为空
        if (CollectionUtils.isEmpty(commentIds)) {
            return DataVo.error("请选择待删除的评论"); // 新增空列表提示
        }

        // 2. 校验所有评论是否存在（避免删除不存在的ID）
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Comment::getId, commentIds); // 按ID列表查询
        List<Comment> existComments = commentMapper.selectList(queryWrapper);

        // 若查询到的存在评论数 ≠ 传入的ID数，说明有无效ID
        if (existComments.size() != commentIds.size()) {
            return DataVo.error("部分评论不存在，无法批量删除");
        }

        // 3. 执行批量删除（MyBatis-Plus自带批量删除方法，效率高于循环单删）
        int deleteCount = commentMapper.deleteBatchIds(commentIds);

        // 4. 校验删除结果（确保所有ID都删除成功）
        if (deleteCount != commentIds.size()) {
            return DataVo.error(MessageConstant.DELETE + MessageConstant.FAILED); // 新增批量删除消息常量
        }

        // 5. 返回批量删除成功结果
        return DataVo.success(MessageConstant.DELETE + MessageConstant.SUCCESS);
    }

    @Override
    @Cacheable(value = "commentCache", key = "'song_' + #commentSongDto.songId + '_' + #commentSongDto.pageNum + '_' + #commentSongDto.pageSize")
    public DataVo<PageResult<CommentVo2>> getSongComments(CommentSongDto2 commentSongDto) {
        try {
            // 1. 创建分页对象
            Page<Comment> page = new Page<>(commentSongDto.getPageNum(), commentSongDto.getPageSize());

            // 2. 构建查询条件
            LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Comment::getSongId, commentSongDto.getSongId());
            queryWrapper.eq(Comment::getType, 0); // 0表示歌曲评论
            queryWrapper.orderByDesc(Comment::getCreateTime);
            queryWrapper.eq(Comment::getIsDelete, 0); // 只查询未删除的评论

            // 3. 执行分页查询
            IPage<Comment> commentPage = baseMapper.selectPage(page, queryWrapper);

            // 4. 处理查询结果
            if (commentPage.getRecords().isEmpty()) {
                return DataVo.success(MessageConstant.DATA_NOT_FOUND, new PageResult<>(0L, null));
            }

            // 5. 转换为VO（这里需要你根据实际情况获取用户信息）
            List<CommentVo2> commentVOS = commentPage.getRecords().stream().map(comment -> {
                CommentVo2 vo = new CommentVo2();
                vo.setCommentId(comment.getId());
                vo.setUserId(comment.getUserId());
                vo.setContent(comment.getContent());
                vo.setCreateTime(comment.getCreateTime().toLocalDate());
                vo.setLikeCount(comment.getLikeCount());

                // 这里需要根据你的用户服务获取用户信息
                // 暂时使用默认值，你需要根据实际情况实现
                vo.setUsername("用户" + comment.getUserId());
                vo.setUserAvatar(null); // 设置为null，前端会使用默认头像

                return vo;
            }).collect(Collectors.toList());

            // 6. 封装分页结果
            PageResult<CommentVo2> pageResult = new PageResult<>(
                    commentPage.getTotal(),
                    commentVOS
            );

            return DataVo.success(pageResult);
        } catch (Exception e) {
            log.error("获取歌曲评论失败:", e);
            return DataVo.error("获取评论失败");
        }
    }

    //删除歌曲评论
    @Override
    public DataVo deleteSongComment(Long commentId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        // 调试日志
        log.info("尝试删除评论，评论ID: {}, 当前用户ID: {}", commentId, userId);

        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            log.warn("评论不存在，评论ID: {}", commentId);
            return DataVo.error(MessageConstant.NOT_FOUND);
        }

        log.info("评论信息: 评论ID: {}, 用户ID: {}, 评论内容: {}", comment.getId(), comment.getUserId(), comment.getContent());

        if (!Objects.equals(comment.getUserId(), userId)) {
            log.warn("权限验证失败：当前用户ID{}与评论用户ID{}不一致", userId, comment.getUserId());
            return DataVo.error(MessageConstant.NO_PERMISSION);
        }

        if (commentMapper.deleteById(commentId) == 0) {
            log.error("删除评论失败，评论ID: {}", commentId);
            return DataVo.error(MessageConstant.DELETE + MessageConstant.FAILED);
        }

        log.info("评论删除成功，评论ID: {}", commentId);
        return DataVo.success(MessageConstant.DELETE + MessageConstant.SUCCESS);
    }

    // 添加歌曲评论
    @Override
    @CacheEvict(cacheNames = {"songCache", "commentCache"}, allEntries = true)
    public DataVo addSongComment(CommentSongDTO commentSongDTO) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setSongId(commentSongDTO.getSongId());
        comment.setContent(commentSongDTO.getContent());
        comment.setType(0);
        comment.setCreateTime(LocalDateTime.now());
        comment.setLikeCount(0L);

        if (commentMapper.insert(comment) == 0) {
            return DataVo.error(MessageConstant.ADD + MessageConstant.FAILED);
        }
        return DataVo.success(MessageConstant.ADD + MessageConstant.SUCCESS);
    }

    // 添加歌单评论
    @Override
    @CacheEvict(cacheNames = {"playlistCache", "commentCache"}, allEntries = true)
    public DataVo addPlaylistComment(CommentPlaylistDTO commentPlaylistDTO) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setPlaylistId(commentPlaylistDTO.getPlaylistId());
        comment.setContent(commentPlaylistDTO.getContent());
        comment.setType(1);
        comment.setCreateTime(LocalDateTime.now());
        comment.setLikeCount(0L);

        if (commentMapper.insert(comment) == 0) {
            return DataVo.error(MessageConstant.ADD + MessageConstant.FAILED);
        }
        return DataVo.success(MessageConstant.ADD + MessageConstant.SUCCESS);
    }

    // 点赞评论
    @Override
    @CacheEvict(cacheNames = {"songCache", "playlistCache", "commentCache"}, allEntries = true)
    public DataVo likeComment(Long commentId) {
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            return DataVo.error(MessageConstant.NOT_FOUND);
        }
        if (comment.getLikeCount() == null) {
            comment.setLikeCount(0L);
        }
        comment.setLikeCount(comment.getLikeCount() + 1);

        if (commentMapper.updateById(comment) == 0) {
            return DataVo.error(MessageConstant.FAILED);
        }
        return DataVo.success(MessageConstant.SUCCESS);
    }

    // 取消点赞评论
    @Override
    @CacheEvict(cacheNames = {"songCache", "playlistCache", "commentCache"}, allEntries = true)
    public DataVo cancelLikeComment(Long commentId) {
        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            return DataVo.error(MessageConstant.NOT_FOUND);
        }
        if (comment.getLikeCount() == null) {
            comment.setLikeCount(0L);
        }
        comment.setLikeCount(comment.getLikeCount() - 1);

        if (commentMapper.updateById(comment) == 0) {
            return DataVo.error(MessageConstant.FAILED);
        }
        return DataVo.success(MessageConstant.SUCCESS);
    }

    //前台删除评论
    @Override
    @CacheEvict(cacheNames = {"songCache", "playlistCache", "commentCache"}, allEntries = true)
    public DataVo deleteComment(Long commentId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        Comment comment = commentMapper.selectById(commentId);
        if (comment == null) {
            return DataVo.error(MessageConstant.NOT_FOUND);
        }
        if (!Objects.equals(comment.getUserId(), userId)) {
            return DataVo.error(MessageConstant.NO_PERMISSION);
        }

        if (commentMapper.deleteById(commentId) == 0) {
            return DataVo.error(MessageConstant.DELETE + MessageConstant.FAILED);
        }
        return DataVo.success(MessageConstant.DELETE + MessageConstant.SUCCESS);
    }

}